<template>
  <van-form @submit="onSubmit">
    <div class="form-header">
      <h3>注册新账户</h3>
    </div>
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          name="userAccount"
          label="账号"
          placeholder="请输入账号"
          :rules="[{ required: true, message: '请填写账号' }]"
          class="form-field"/>
      <van-field
          v-model="userPassword"
          type="password"
          name="userPassword"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
          class="form-field"/>
      <van-field
          v-model="checkPassword"
          type="password"
          name="checkPassword"
          label="确认密码"
          placeholder="请确认密码"
          :rules="[{ required: true, message: '请确认密码' }]"
          class="form-field"/>
      <van-field
          v-model="planetCode"
          name="planetCode"
          label="星球编码"
          placeholder="请输入星球编码"
          :rules="[{ required: true, message: '请填写星球编码' }]"
          class="form-field"/>
    </van-cell-group>
    <div class="submit-button">
      <van-button round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
    <div class="login-link">
      <router-link to="/user/login">已有账号？登录</router-link>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import myAxios from '../plugins/myAxios';
import { showFailToast, showSuccessToast } from 'vant';

const userAccount = ref('');
const userPassword = ref('');
const checkPassword = ref('');
const planetCode = ref('');

const onSubmit = async () => {
  try {
    const res = await myAxios.post('/user/register', {
      userAccount: userAccount.value,
      userPassword: userPassword.value,
      checkPassword: checkPassword.value,
      planetCode: planetCode.value,
    });
    if (res.code === 0 && res.data) {
      showSuccessToast("注册成功");
      // 跳转到登录页
      window.location.href = '/user/login';
    } else {
      showFailToast('注册失败');
    }
  } catch (error) {
    showFailToast('注册失败');
  }
};
</script>

<style scoped>
.form-header {
  text-align: center;
  margin: 24px 0;
}

.form-header h3 {
  font-size: 1.5rem;
  color: #333;
}

.form-field {
  margin-bottom: 12px;
}

.submit-button {
  margin: 24px 16px;
}

.submit-button .van-button {
  background-color: #007bff;
  border: none;
}

.submit-button .van-button:hover {
  background-color: #0056b3;
}

.login-link {
  text-align: center;
  margin: 16px;
}

.login-link a {
  color: #007bff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>
